<template>
  <view class="container">
    <VTabs
      :list="categoryList"
      :current="0"
      :height="screenHeight"
      :chain="false"
      :bar-width="'200rpx'"
      :bar-bg-color="'#f5f5f5'"
      @change="handleTabChange"
      @show-product-detail="showProductDetail"
    />

    <!-- 商品详情弹窗 -->
    <uv-popup
      ref="popupRef"
      mode="bottom"
      :border-radius="20"
      :safe-area-inset-bottom="true"
      :close-on-click-overlay="true"
      @change="handlePopupChange"
    >
      <view class="popup-content">
        <!-- 关闭按钮 -->
        <view class="popup-header">
          <view class="close-btn" @click="closePopup">
            <text class="close-icon">×</text>
          </view>
        </view>

        <!-- 商品信息 -->
        <view class="product-detail" v-if="selectedProduct">
          <view class="product-image">
            <image
              :src="selectedProduct.icon || '/static/default-icon.png'"
              class="detail-img"
              mode="aspectFit"
            />
          </view>
          <view class="product-detail-info">
            <text class="detail-name">{{ selectedProduct.name }}</text>
            <view class="detail-price">
              <text class="detail-current-price"
                >¥{{ selectedProduct.price }}</text
              >
              <text
                v-if="selectedProduct.originalPrice"
                class="detail-original-price"
              >
                ¥{{ selectedProduct.originalPrice }}
              </text>
            </view>
            <view class="detail-sales">
              <text class="detail-sales-text"
                >库存：{{ selectedProduct.stock || 1000 }}</text
              >
              <text class="detail-sales-text"
                >月售：{{ selectedProduct.sales || 0 }}</text
              >
            </view>
          </view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-section">
          <text class="spec-title">规格选择</text>
          <view class="spec-options">
            <view
              v-for="(spec, index) in specOptions"
              :key="index"
              :class="['spec-item', { active: selectedSpec === spec }]"
              @click="selectSpec(spec)"
            >
              <text class="spec-text">{{ spec }}</text>
            </view>
          </view>
        </view>

        <!-- 购买数量 -->
        <view class="quantity-section">
          <text class="quantity-title">购买数量</text>
          <view class="quantity-controls">
            <view class="quantity-btn" @click="decreaseQuantity">
              <text class="quantity-icon">-</text>
            </view>
            <text class="quantity-input">{{ quantity }}</text>
            <view class="quantity-btn" @click="increaseQuantity">
              <text class="quantity-icon">+</text>
            </view>
          </view>
        </view>

        <!-- 总价 -->
        <view class="total-section" v-if="selectedProduct">
          <text class="total-text"
            >合计金额：¥{{
              (selectedProduct.price * quantity).toFixed(2)
            }}</text
          >
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons">
          <view class="add-cart-btn" @click="addToCart">
            <text class="btn-text">🛒 加入购物车</text>
          </view>
          <view class="buy-now-btn" @click="buyNow">
            <text class="btn-text">立即购买</text>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import VTabs from '@/components/VTabs.vue';

const screenHeight = ref('100vh');

// 弹窗相关
const popupRef = ref(null);
const selectedProduct = ref(null);
const selectedSpec = ref('大份');
const quantity = ref(1);

// 规格选项
const specOptions = ref(['大份', '中份', '小份']);

onMounted(() => {
  // 获取系统信息
  uni.getSystemInfo({
    success: (res) => {
      // 计算可用高度 = 屏幕高度 - 状态栏高度 - 导航栏高度
      const availableHeight = res.windowHeight;
      screenHeight.value = availableHeight + 'px';
    },
  });
});

const categoryList = [
  {
    id: 1,
    name: '搜索代付',
    products: [
      {
        id: 1,
        name: '北京丰台机场——三亚凤凰机场',
        price: 355.0,
        originalPrice: 544.0,
        sales: 1000,
        rating: 5,
        reviewCount: 186,
        icon: '/static/logo.png',
      },
      {
        id: 2,
        name: '杭州萧山机场——北京大兴机场',
        price: 468.0,
        originalPrice: 568.0,
        sales: 1000,
        rating: 5,
        reviewCount: 152,
        icon: '/static/logo.png',
      },
    ],
  },
  {
    id: 2,
    name: '运营外卖',
    products: [
      {
        id: 3,
        name: '上海浦东T2——成都天府T2',
        price: 395.0,
        originalPrice: 488.0,
        sales: 1000,
        rating: 5,
        reviewCount: 134,
        icon: '/static/logo.png',
      },
    ],
  },
  {
    id: 3,
    name: '水果零食',
    products: [
      {
        id: 4,
        name: '新鲜苹果礼盒装',
        price: 68.0,
        originalPrice: 88.0,
        sales: 2500,
        rating: 5,
        reviewCount: 1205,
        icon: '/static/logo.png',
      },
      {
        id: 5,
        name: '进口车厘子',
        price: 128.0,
        originalPrice: 158.0,
        sales: 1800,
        rating: 5,
        reviewCount: 896,
        icon: '/static/logo.png',
      },
    ],
  },
  {
    id: 4,
    name: '酒店床灯',
    products: [
      {
        id: 6,
        name: '智能感应床头灯',
        price: 199.0,
        originalPrice: 299.0,
        sales: 856,
        rating: 5,
        reviewCount: 425,
        icon: '/static/logo.png',
      },
    ],
  },
  {
    id: 5,
    name: '高端出行',
    products: [
      {
        id: 7,
        name: '商务专车服务',
        price: 288.0,
        originalPrice: 368.0,
        sales: 1256,
        rating: 5,
        reviewCount: 632,
        icon: '/static/logo.png',
      },
    ],
  },
];

const handleTabChange = (index, item) => {
  console.log('选中分类:', index, item);
};

// 显示商品详情弹窗
const showProductDetail = (product) => {
  console.log('显示商品详情:', product);
  selectedProduct.value = product;
  selectedSpec.value = '大份';
  quantity.value = 1;

  // 使用ref调用popup的open方法
  if (popupRef.value) {
    popupRef.value.open('bottom');
  }
};

// 关闭弹窗
const closePopup = () => {
  if (popupRef.value) {
    popupRef.value.close();
  }
};

// 处理弹窗状态变化
const handlePopupChange = (event) => {
  console.log('弹窗状态变化:', event);
  if (!event.show) {
    selectedProduct.value = null;
  }
};

// 选择规格
const selectSpec = (spec) => {
  selectedSpec.value = spec;
};

// 增加数量
const increaseQuantity = () => {
  quantity.value++;
};

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 加入购物车
const addToCart = () => {
  const cartData = {
    product: selectedProduct.value,
    spec: selectedSpec.value,
    quantity: quantity.value,
    totalPrice: (selectedProduct.value.price * quantity.value).toFixed(2),
  };

  console.log('添加到购物车:', cartData);

  uni.showToast({
    title: '已添加到购物车',
    icon: 'success',
    duration: 1500,
  });

  closePopup();
};

// 立即购买
const buyNow = () => {
  const orderData = {
    product: selectedProduct.value,
    spec: selectedSpec.value,
    quantity: quantity.value,
    totalPrice: (selectedProduct.value.price * quantity.value).toFixed(2),
  };

  console.log('立即购买:', orderData);

  uni.showToast({
    title: '立即购买',
    icon: 'success',
    duration: 1500,
  });

  closePopup();
};
</script>

<style>
page {
  height: 100%;
  overflow: hidden;
  width: 100%;
}

.container {
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  width: 100%;
}

/* 弹窗样式 */
.popup-content {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx;
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
  max-height: calc(85vh - 50rpx);
  overflow-y: auto;
  box-sizing: border-box;
}

.popup-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20rpx;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f5f5;
}

.close-icon {
  font-size: 40rpx;
  color: #999;
  font-weight: bold;
}

.product-detail {
  display: flex;
  margin-bottom: 40rpx;
  padding-bottom: 40rpx;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 30rpx;
  flex-shrink: 0;
}

.detail-img {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  background-color: #f8f8f8;
}

.product-detail-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.detail-name {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.detail-price {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.detail-current-price {
  font-size: 48rpx;
  color: #ff4444;
  font-weight: bold;
  margin-right: 16rpx;
}

.detail-original-price {
  font-size: 32rpx;
  color: #999;
  text-decoration: line-through;
}

.detail-sales {
  display: flex;
  gap: 24rpx;
}

.detail-sales-text {
  font-size: 28rpx;
  color: #666;
}

.spec-section {
  margin-bottom: 40rpx;
}

.spec-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 24rpx;
  display: block;
}

.spec-options {
  display: flex;
  gap: 20rpx;
  flex-wrap: wrap;
}

.spec-item {
  padding: 16rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #ffffff;
  transition: all 0.3s;
}

.spec-item.active {
  border-color: #333;
  background-color: #333;
}

.spec-text {
  font-size: 28rpx;
  color: #666;
}

.spec-item.active .spec-text {
  color: #ffffff;
}

.quantity-section {
  margin-bottom: 40rpx;
}

.quantity-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 24rpx;
  display: block;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  transition: all 0.3s;
}

.quantity-btn:active {
  background-color: #f0f0f0;
}

.quantity-icon {
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.quantity-input {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  min-width: 80rpx;
  text-align: center;
}

.total-section {
  margin-bottom: 40rpx;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.total-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  display: block;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

.add-cart-btn,
.buy-now-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.add-cart-btn {
  background-color: #ffffff;
  border: 2rpx solid #333;
}

.add-cart-btn:active {
  background-color: #f0f0f0;
}

.buy-now-btn {
  background-color: #333;
}

.buy-now-btn:active {
  background-color: #555;
}

.add-cart-btn .btn-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.buy-now-btn .btn-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 底部安全区域适配 */
@supports (bottom: env(safe-area-inset-bottom)) {
  .popup-content {
    padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
  }

  .action-buttons {
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }
}

/* 针对有底部导航栏的页面 */
.action-buttons {
  min-height: 88rpx;
  flex-shrink: 0;
}
</style>
